package server.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import server.demo.dto.ApiResponse;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/test")
public class TestController {
    
    @Autowired
    private DataSource dataSource;
    
    @GetMapping("/db")
    public ApiResponse<Map<String, Object>> testDatabaseConnection() {
        Map<String, Object> result = new HashMap<>();
        try {
            Connection connection = dataSource.getConnection();
            result.put("connected", true);
            result.put("database", connection.getCatalog());
            result.put("url", connection.getMetaData().getURL());
            connection.close();
            return ApiResponse.success(result);
        } catch (Exception e) {
            result.put("connected", false);
            result.put("error", e.getMessage());
            return ApiResponse.error("数据库连接失败", result);
        }
    }
}